//
//  QCSingleton.m
//  QCAppProject
//
//  Created by yjl on 2021/8/19.
//

#import "QCSingleton.h"

@implementation QCSingleton

#define kUserInforKey @"FDD_User_Key"

static QCSingleton *_instance = nil;

//重写get方法
@synthesize userInfo = _userInfo;

+ (QCSingleton *)instance
{
    static dispatch_once_t oneToken;
    dispatch_once(&oneToken, ^{
        _instance = [[self alloc]init];
    });
    return _instance;
}


- (instancetype)init {
    if (self == [super init]) {
        _account = @"";
    }
    return self;
}

- (NSString *)account {
    return self.userInfo.account;
}

- (void)setUserInfo:(QCUserInfo *)userInfo {
    _userInfo = userInfo;
    if (userInfo) {
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:userInfo];
        [UD setObject:data forKey:kUserInforKey];
        [UD synchronize];
    }else {
        [self removeUserInfo];
    }
}

//当改变用户某个信息是（eg：修改用户名字），调用这个方法来保存（重置）信息
-(void)saveUserInfoToLocal {
    if (_userInfo) {
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:_userInfo];
        [UD setObject:data forKey:kUserInforKey];
        [UD synchronize];
    }
}

- (QCUserInfo *)userInfo {
    if (_userInfo == nil) {
        NSData *data = [UD objectForKey:kUserInforKey];
        if (data) {
            _userInfo = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        }
    }
    return _userInfo;
}

-(void)removeUserInfo{
    [UD removeObjectForKey:kUserInforKey];
    [UD synchronize];
}

@end
